﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShareFrame.Util.Helper
{
    /// <summary>
    /// 父类对象转子类对象，复制属性值
    /// </summary>
    public static class AutoAdaptation
    {
        /// <summary>
        /// 自动将父类对象赋值转成子类对象
        /// </summary>
        /// <typeparam name="TParent">父类型</typeparam>
        /// <typeparam name="TChild">子类型</typeparam>
        /// <param name="parent">父类对象</param>
        /// <returns>子类对象</returns>
        public static TChild AutoCopy<TParent, TChild>(TParent parent) where TChild : TParent, new()
        {
            TChild child = new TChild();
            var ParentType = typeof(TParent);
            var Properties = ParentType.GetProperties();
            foreach (var Propertie in Properties)
            {
                //循环遍历属性
                if (Propertie.CanRead && Propertie.CanWrite)
                {
                    //进行属性拷贝
                    Propertie.SetValue(child, Propertie.GetValue(parent, null), null);
                }
            }
            return child;
        }
    }
}
